<script setup lang="ts">
import { onUnmounted, ref } from 'vue';

const count = ref(0);

let timer = -1;
const sendCode = () => {
  // 如果倒计时没结束，直接退出
  if (count.value !== 0) return;

  // 初始化倒计时
  count.value = 60;

  // 启动定时器
  timer = window.setInterval(() => {
    console.log('定时器正在运行中...');
    // 倒计时变量
    count.value--;
    // 倒计时结束
    if (count.value === 0) {
      // 清理定时器
      clearInterval(timer);
    }
  }, 1000);
};

// 组件卸载时，清理定时器
onUnmounted(() => {
  clearInterval(timer);
});
</script>

<template>
  <h1>倒计时业务封装测试</h1>
  <button @click="sendCode">
    {{ count === 0 ? '点击发送验证码' : count }}
  </button>
  <RouterLink to="/">去首页</RouterLink>
  <div>--------------------------</div>
</template>
